package belf.migrate.engine.admin;

import belf.migrate.api.util.EngineConf;
import belf.migrate.engine.admin.handler.ConfigHandler;
import belf.migrate.engine.admin.handler.ConnectorHandler;
import belf.migrate.engine.admin.handler.JobHandler;
import belf.migrate.engine.admin.handler.SqlHandler;
import lombok.extern.slf4j.Slf4j;
import spark.Spark;

import static spark.Spark.*;

@Slf4j
public class SparkServer {

    public void start() {
        port(EngineConf.getInstance().getInt("http.port", 9588));
        get("/hello", (req, res) -> "Hello Belf");

        // 注册所有HTTP API
        api();

        before((request, response) -> {
            log.info("Received request:");
            log.info("Method: " + request.requestMethod());
            log.info("Path: " + request.url());
            log.info("Query Params: " + request.queryString());
            log.info("Request Body: " + request.body());
        });

        after((request, response) -> {
            log.info("Response Status: " + response.status());
            log.info("Response Body: " + response.body());
        });

        log.info("Spark Server started successfully.");
    }

    public void api() {
        path("/job", () -> { //Job调度的路由注册
            JobHandler.setupRoutes();

        });
        path("/config", () -> { //引擎参数配置的路由注册
            ConfigHandler.setupRoutes();

        });
        path("/connector", () -> { //连接器相关的路由注册
            ConnectorHandler.setupRoutes();

        });
        path("/sql", () -> { //sql相关的路由注册
            SqlHandler.setupRoutes();

        });
    }

    public void close() {
        Spark.stop();
    }
}
